package com.gxnu.edu.cn.ttxxt.service.Impl;

import com.gxnu.edu.cn.ttxxt.entity.Friendship;
import com.gxnu.edu.cn.ttxxt.entity.GroupsMembers;
import com.gxnu.edu.cn.ttxxt.entity.Notifications;
import com.gxnu.edu.cn.ttxxt.mapper.FriendshipRepository;
import com.gxnu.edu.cn.ttxxt.mapper.GroupMemberRepository;
import com.gxnu.edu.cn.ttxxt.mapper.NotificationRepository;
import com.gxnu.edu.cn.ttxxt.service.NotificationService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

@Service
public class NotificationServiceImpl implements NotificationService {

    @Autowired
    private NotificationRepository notificationRepository;
    @Autowired
    private FriendshipRepository friendshipRepository;
    @Autowired
    private GroupMemberRepository groupMemberRepository;

    @Override
    @Transactional
    public void sendNotification(Long receiverId, Long senderId, Integer type, String content) {
        // 检查是否已存在相同类型的未处理通知
        if (type == 1 || type == 4) { // 好友请求或群邀请才需要检查重复
            boolean exists = notificationRepository.existsBySenderIdAndReceiverIdAndType(
                    senderId, receiverId, type);
            if (exists) {
                return; // 避免重复发送相同类型的通知
            }
        }

        Notifications notifications = new Notifications();
        notifications.setReceiverId(receiverId);
        notifications.setSenderId(senderId);
        notifications.setType(type);
        notifications.setContent(content);
        notifications.setStatus(1); // 1-未读
        notifications.setCreateTime(new Date());

        notificationRepository.insert(notifications);
    }

    @Override
    public List<Notifications> getNotifications(Long userId) {
        return notificationRepository.findByReceiverId(userId);
    }

    @Override
    public List<Notifications> getUnreadNotifications(Long userId) {
        return notificationRepository.findByReceiverIdAndStatus(userId, 1); // 1-未读
    }

    @Override
    @Transactional
    public void markNotificationAsRead(Long notificationId) {
        Notifications notifications = notificationRepository.selectById(notificationId);
        if (notifications != null && notifications.getStatus() == 1) {
            notifications.setStatus(2); // 2-已读
            notificationRepository.updateById(notifications);
        }
    }

    @Override
    @Transactional
    public void markAllNotificationsAsRead(Long userId) {
        notificationRepository.updateStatusByReceiverId(userId, 1, 2); // 将所有未读(1)标记为已读(2)
    }

    @Override
    @Transactional
    public String processNotification(Long notificationId, Integer status) {
        Notifications notifications = notificationRepository.selectById1(notificationId);

        // 1. 检查通知是否存在
        if (notifications == null) {
            return "NOTIFICATION_NOT_FOUND"; // 返回状态码而非抛异常
        }

        // 2. 检查状态是否合法
        if (status != 2 && status != 3) {
            return "INVALID_STATUS";
        }

//        // 3. 检查通知当前状态（如果需要）
//        if (notifications.getStatus() != 1) { // 假设 1 是待处理状态
//            return "NOTIFICATION_ALREADY_PROCESSED";
//        }

        try {
            // 4. 正常处理逻辑
            notifications.setType(2);
            notifications.setStatus(status);
            notificationRepository.updateById1(notifications.getNotificationId());

            // 5. 创建反向通知（同意后通知对方）
            Notifications reverseNotification = new Notifications();
            BeanUtils.copyProperties(notifications, reverseNotification);
            reverseNotification.setNotificationId(null);
            reverseNotification.setReceiverId(notifications.getSenderId());
            reverseNotification.setSenderId(notifications.getReceiverId());
            reverseNotification.setContent("添加好友成功");
            reverseNotification.setStatus(3);
            reverseNotification.setType(2); // 新通知状态为待处理
            reverseNotification.setCreateTime(new Date());
            notificationRepository.insert(reverseNotification);

            Friendship friendship = new Friendship();
            friendship.setUserId(notifications.getReceiverId());
            friendship.setFriendId(notifications.getSenderId());
            friendship.setStatus(1);
            friendship.setCreateTime(new Date());
            friendship.setUpdateTime(new Date());
            friendshipRepository.add(friendship);

            return "SUCCESS"; // 返回成功状态
        } catch (Exception e) {
            // 记录异常到日志（生产环境）
            // logger.error("处理通知失败", e);
            // 这里可以根据异常类型进一步细化处理，例如数据库异常等
            return "INTERNAL_SERVER_ERROR";
        }
    }
    @Override
    public List<Notifications> getNotificationsFrendApple(Long userId) {
        return notificationRepository.findByReceiverIdAndStatus(userId, 1);
    }

    @Override
    public String rejectNotification(Long notificationId, Integer status) {
        Notifications notifications = notificationRepository.selectById1(notificationId);

        // 1. 检查通知是否存在
        if (notifications == null) {
            return "NOTIFICATION_NOT_FOUND"; // 返回状态码而非抛异常
        }



        try {
            // 4. 正常处理逻辑
            notifications.setType(3);
            notifications.setStatus(3);
            notificationRepository.updateById1(notifications.getNotificationId());
            // 5. 创建反向通知（拒绝后通知对方）
            Notifications reverseNotification = new Notifications();
            BeanUtils.copyProperties(notifications, reverseNotification);
            reverseNotification.setNotificationId(null);
            reverseNotification.setReceiverId(notifications.getSenderId());
            reverseNotification.setSenderId(notifications.getReceiverId());
            reverseNotification.setContent("添加好友被拒绝");
            reverseNotification.setStatus(3);
            reverseNotification.setType(3); // 新通知状态为待处理
            reverseNotification.setCreateTime(new Date());
            notificationRepository.insert(reverseNotification);
            return "SUCCESS"; // 返回成功状态
        } catch (Exception e) {
            // 记录异常到日志（生产环境）
            // logger.error("处理通知失败", e);
            // 这里可以根据异常类型进一步细化处理，例如数据库异常等
            return "INTERNAL_SERVER_ERROR";
        }
    }

    /**
     * 处理好友请求通知
     */
    private void handleFriendRequest(Notifications notifications, Integer status) {
        Long senderId = notifications.getSenderId();
        Long receiverId = notifications.getReceiverId();

        if (status == 3) { // 接受好友请求
            // 1. 检查是否已存在好友关系
            if (friendshipRepository.existsByUserIdAndFriendId(receiverId, senderId)) {
                throw new RuntimeException("已是好友关系，无需重复添加");
            }

            // 2. 创建双向好友关系
            createBidirectionalFriendship(receiverId, senderId);

            // 3. 发送好友请求通过通知
            sendAcceptFriendNotification(senderId, receiverId);

        } else if (status == 4) { // 拒绝好友请求
            // 发送好友请求拒绝通知
            sendRejectFriendNotification(senderId, receiverId);
        }
    }

    /**
     * 创建双向好友关系
     */
    private void createBidirectionalFriendship(Long userId1, Long userId2) {
        // 创建第一方向好友关系
        Friendship friendship1 = new Friendship();
        friendship1.setUserId(userId1);
        friendship1.setFriendId(userId2);
        friendship1.setStatus(1); // 1-正常
        friendshipRepository.insert(friendship1);

        // 创建第二方向好友关系
        Friendship friendship2 = new Friendship();
        friendship2.setUserId(userId2);
        friendship2.setFriendId(userId1);
        friendship2.setStatus(1); // 1-正常
        friendshipRepository.insert(friendship2);
    }

    /**
     * 发送好友请求接受通知
     */
    private void sendAcceptFriendNotification(Long senderId, Long receiverId) {
        String content = String.format("用户 %d 已接受您的好友请求", receiverId);
        Notifications acceptNotifications = new Notifications();
        acceptNotifications.setReceiverId(senderId);
        acceptNotifications.setSenderId(receiverId);
        acceptNotifications.setType(2); // 2-好友请求通过
        acceptNotifications.setContent(content);
        acceptNotifications.setStatus(1); // 1-未读
        acceptNotifications.setCreateTime(new Date());
        notificationRepository.insert(acceptNotifications);
    }

    /**
     * 发送好友请求拒绝通知
     */
    private void sendRejectFriendNotification(Long senderId, Long receiverId) {
        String content = String.format("用户 %d 已拒绝您的好友请求", receiverId);
        Notifications rejectNotifications = new Notifications();
        rejectNotifications.setReceiverId(senderId);
        rejectNotifications.setSenderId(receiverId);
        rejectNotifications.setType(3); // 3-好友请求拒绝
        rejectNotifications.setContent(content);
        rejectNotifications.setStatus(1); // 1-未读
        rejectNotifications.setCreateTime(new Date());
        notificationRepository.insert(rejectNotifications);
    }

    /**
     * 处理群邀请通知
     */
    private void handleGroupInvitation(Notifications notifications, Integer status) {
        try {
            // 假设content中存储的是群组ID
            Long groupId = Long.parseLong(notifications.getContent());
            Long inviterId = notifications.getSenderId();
            Long inviteeId = notifications.getReceiverId();

            if (status == 3) { // 接受群邀请
                // 1. 检查用户是否已在群中
                if (groupMemberRepository.existsByUserIdAndGroupId(inviteeId, groupId)) {
                    throw new RuntimeException("用户已在群组中");
                }

                // 2. 添加用户到群组
                addUserToGroup(groupId, inviteeId);

                // 3. 发送群邀请接受通知
                sendAcceptGroupInvitationNotification(inviterId, inviteeId, groupId);

            } else if (status == 4) { // 拒绝群邀请
                // 发送群邀请拒绝通知
                sendRejectGroupInvitationNotification(inviterId, inviteeId);
            }
        } catch (NumberFormatException e) {
            throw new RuntimeException("群组ID格式错误");
        }
    }

    /**
     * 添加用户到群组
     */
    private void addUserToGroup(Long groupId, Long userId) {
        GroupsMembers member = new GroupsMembers();
        member.setGroupId(groupId);
        member.setUserId(userId);
        member.setRole(1); // 1-普通成员
        groupMemberRepository.insert(member);
    }

    /**
     * 发送群邀请接受通知
     */
    private void sendAcceptGroupInvitationNotification(Long inviterId, Long inviteeId, Long groupId) {
        String content = String.format("用户 %d 已接受您的群邀请，加入群组 %d", inviteeId, groupId);
        Notifications acceptNotifications = new Notifications();
        acceptNotifications.setReceiverId(inviterId);
        acceptNotifications.setSenderId(inviteeId);
        acceptNotifications.setType(2); // 2-操作成功通知
        acceptNotifications.setContent(content);
        acceptNotifications.setStatus(1); // 1-未读
        acceptNotifications.setCreateTime(new Date());
        notificationRepository.insert(acceptNotifications);
    }

    /**
     * 发送群邀请拒绝通知
     */
    private void sendRejectGroupInvitationNotification(Long inviterId, Long inviteeId) {
        String content = String.format("用户 %d 已拒绝您的群邀请", inviteeId);
        Notifications rejectNotifications = new Notifications();
        rejectNotifications.setReceiverId(inviterId);
        rejectNotifications.setSenderId(inviteeId);
        rejectNotifications.setType(3); // 3-操作拒绝通知
        rejectNotifications.setContent(content);
        rejectNotifications.setStatus(1); // 1-未读
        rejectNotifications.setCreateTime(new Date());
        notificationRepository.insert(rejectNotifications);
    }
}